#!/bin/sh
#
# Startup script for the Apache JMeter server
#
# chkconfig: - 85 15
# description: Apache JMeter server
# processname: tomcat
# pidfile: /var/run/$JMETER.pid
# config:
#set -x
# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

# Set Tomcat environment.
JAVA_HOME=/usr/java/jdk
PATH=/usr/java/jdk/bin:$PATH
JMETER=jmeter-server
JMETER_USER=tomcat5
if [ "$JMETER_USER" = "changeme" ] ;
then echo "User $JMETER_USER is the default, please create a new one in order to configure jmeter!" && exit 0
elif [ "`grep ^$JMETER_USER: /etc/passwd|cut -d ":" -f1`" != "$JMETER_USER" ];
then echo "User $JMETER_USER not exists, please create it!" && exit 0
fi
JMETER_HOME=/home/$JMETER_USER
JAVA_PID=`ps ax --width=1000 | grep "[A]pacheJMeter.jar -Dserver_port=1099 -s -j jmeter-server.log"|awk '{printf $1 ""}'`

[ -f $JMETER_HOME/jmeter/bin/jmeter-server ] || exit 0
[ -f $JMETER_HOME/jmeter/bin/jmeter ] || exit 0

#export PATH=$PATH:/usr/bin:/usr/local/bin

# See how we were called.
case "$1" in
  start)
        # Start daemon.
        [ -n "$JAVA_PID" ] && echo "$JMETER already started" && exit 0
	echo -n "Starting $JMETER: "
        runuser -l $JMETER_USER -c "$JMETER_HOME/jmeter/bin/$JMETER 2>&1 &"
        RETVAL=$?
        MODE="normal"
        echo "$JMETER started in $MODE mode"
        [ $RETVAL = 0 ] && touch /var/lock/subsys/$JMETER
        ;;
  stop)
        # Stop daemons.
	[ -z "$JAVA_PID" ] && echo "$JMETER already stopped" && exit 0
	echo -n "Shutting down $JMETER: "
        kill $JAVA_PID
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && rm -f /var/lock/subsys/$JMETER
        ;;
  restart)
        $0 stop
        $0 start
        ;;
  condrestart)
       [ -e /var/lock/subsys/$JMETER ] && $0 restart
       ;;
  status)
        if [ -n "$JAVA_PID" ]; then
		MODE="RUNNING pid $JAVA_PID"
	else
		MODE="STOPPED"
	fi
	echo "$JMETER is $MODE"
        ;;
  *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
esac

exit 0
